// 全局变量
let accounts = [];
let marketers = ["请选择营销人"];
let products = ["请选择产品名称"];
let sortConfig = {
    column: 'id',
    direction: 'desc'
};

// API基础URL
const API_BASE_URL = 'http://localhost:5000/api';

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化日期为今天
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('date').value = today;
    document.getElementById('batchDate').value = today;
    
    // 加载数据和配置
    initializeApp();
});

// 初始化应用
async function initializeApp() {
    // 加载数据
    await loadData();
    await loadConfig();
    
    // 绑定事件
    bindEvents();
    
    // 初始化界面
    updateAccountList();
    updateComboboxes();
}

// 绑定事件
function bindEvents() {
    console.log('开始绑定事件');
    
    // 添加记录表单提交
    const accountForm = document.getElementById('accountForm');
    if (accountForm) {
        accountForm.addEventListener('submit', function(e) {
            e.preventDefault();
            addAccount();
        });
    }
    
    // 批量录入按钮
    const batchEntryBtn = document.getElementById('batchEntryBtn');
    if (batchEntryBtn) {
        batchEntryBtn.addEventListener('click', openBatchEntry);
    }
    
    // 导出按钮
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', exportData);
    }
    
    // 管理按钮
    const manageBtn = document.getElementById('manageBtn');
    if (manageBtn) {
        manageBtn.addEventListener('click', function() {
            openManageWindow();
        });
    }
    
    // 批量录入模态框中的事件
    const addProductRowBtn = document.getElementById('addProductRowBtn');
    if (addProductRowBtn) {
        addProductRowBtn.addEventListener('click', addProductRow);
    }
    
    const saveBatchBtn = document.getElementById('saveBatchBtn');
    if (saveBatchBtn) {
        saveBatchBtn.addEventListener('click', saveBatchRecords);
    }
    
    // 表格列标题点击排序
    const sortHeaders = document.querySelectorAll('#accountsTable th[data-sort]');
    sortHeaders.forEach(th => {
        th.addEventListener('click', function() {
            const column = this.getAttribute('data-sort');
            sortBy(column);
        });
    });
    
    // 动态绑定删除按钮事件（使用事件委托）
    const accountsTableBody = document.getElementById('accountsTableBody');
    if (accountsTableBody) {
        accountsTableBody.addEventListener('click', function(e) {
            if (e.target.classList.contains('delete-btn') || e.target.closest('.delete-btn')) {
                const btn = e.target.closest('.delete-btn');
                const id = parseInt(btn.getAttribute('data-id'));
                deleteAccount(id);
            }
            
            // 动态绑定编辑按钮事件（使用事件委托）
            if (e.target.classList.contains('edit-btn') || e.target.closest('.edit-btn')) {
                const btn = e.target.closest('.edit-btn');
                const id = parseInt(btn.getAttribute('data-id'));
                editAccount(id);
            }
        });
    }
    
    // 管理模态框事件绑定
    const manageModal = document.getElementById('manageModal');
    if (manageModal) {
        manageModal.addEventListener('shown.bs.modal', function () {
            // 每次打开模态框时更新列表显示
            updateManageLists();
        });
    }
    
    // 编辑模态框事件绑定
    const saveEditBtn = document.getElementById('saveEditBtn');
    if (saveEditBtn) {
        saveEditBtn.addEventListener('click', saveEditedAccount);
    }
    
    console.log('事件绑定完成');
}

// 绑定管理模态框内的事件
function bindManageEvents() {
    // 绑定标签页切换事件
    const manageTabs = document.getElementById('manageTabs');
    if (manageTabs) {
        manageTabs.addEventListener('click', function(e) {
            if (e.target.matches('[data-bs-toggle="tab"]')) {
                const tabId = e.target.getAttribute('data-bs-target');
                document.querySelectorAll('.tab-pane').forEach(pane => {
                    pane.classList.remove('active', 'show');
                });
                document.querySelector(tabId).classList.add('active', 'show');
            }
        });
    }
    
    // 绑定添加营销人事件
    const addMarketerBtn = document.getElementById('addMarketerBtn');
    if (addMarketerBtn) {
        // 先移除可能已存在的事件监听器
        const newAddMarketerBtn = addMarketerBtn.cloneNode(true);
        addMarketerBtn.parentNode.replaceChild(newAddMarketerBtn, addMarketerBtn);
        
        // 绑定添加营销人事件
        newAddMarketerBtn.addEventListener('click', function(e) {
            e.preventDefault();
            // 确保在营销人标签页激活的状态下添加
            const marketerTab = document.getElementById('marketer-tab');
            const activeTab = document.querySelector('.nav-link.active');
            if (activeTab && activeTab.id !== 'marketer-tab') {
                const bootstrapTab = new bootstrap.Tab(marketerTab);
                bootstrapTab.show();
            }
            addMarketer();
        });
    }
    
    // 绑定添加产品事件
    const addProductBtn = document.getElementById('addProductBtn');
    if (addProductBtn) {
        // 先移除可能已存在的事件监听器
        const newAddProductBtn = addProductBtn.cloneNode(true);
        addProductBtn.parentNode.replaceChild(newAddProductBtn, addProductBtn);
        
        // 绑定添加产品事件
        newAddProductBtn.addEventListener('click', function(e) {
            e.preventDefault();
            // 确保在产品标签页激活的状态下添加
            const productTab = document.getElementById('product-tab');
            const activeTab = document.querySelector('.nav-link.active');
            if (activeTab && activeTab.id !== 'product-tab') {
                const bootstrapTab = new bootstrap.Tab(productTab);
                bootstrapTab.show();
            }
            addProduct();
        });
    }
    
    // 使用事件委托处理删除按钮
    const marketerList = document.getElementById('marketerList');
    if (marketerList) {
        marketerList.addEventListener('click', function(e) {
            if (e.target.closest('.remove-marketer')) {
                const btn = e.target.closest('.remove-marketer');
                const name = btn.getAttribute('data-name');
                removeMarketer(name);
            }
        });
    }
    
    const productList = document.getElementById('productList');
    if (productList) {
        productList.addEventListener('click', function(e) {
            if (e.target.closest('.remove-product')) {
                const btn = e.target.closest('.remove-product');
                const name = btn.getAttribute('data-name');
                removeProduct(name);
            }
        });
    }
}

// 从API加载数据
async function loadData() {
    console.log('开始加载数据...');
    try {
        const response = await fetch(`${API_BASE_URL}/accounts`);
        const result = await response.json();
        console.log('API响应:', result);
        if (result.success) {
            accounts = result.data || [];
            console.log(`成功加载 ${accounts.length} 条记录`);
        } else {
            console.error('加载数据失败:', result.error);
            accounts = [];
        }
    } catch (e) {
        console.error('加载数据失败:', e);
        // 如果API不可用，尝试从LocalStorage加载
        const data = localStorage.getItem('account_data');
        if (data) {
            try {
                accounts = JSON.parse(data);
                console.log(`从LocalStorage加载 ${accounts.length} 条记录`);
            } catch (e) {
                console.error('加载本地数据失败:', e);
                accounts = [];
            }
        } else {
            accounts = [];
        }
    }
    console.log('数据加载完成，当前记录数:', accounts.length);
}

// 保存数据到API
async function saveData() {
    try {
        const response = await fetch(`${API_BASE_URL}/accounts`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ data: accounts }),
        });
        const result = await response.json();
        if (result.success) {
            console.log('数据保存成功');
        } else {
            console.error('数据保存失败:', result.error);
            // 如果API保存失败，尝试保存到LocalStorage作为后备方案
            localStorage.setItem('account_data', JSON.stringify(accounts));
        }
    } catch (e) {
        console.error('保存数据失败:', e);
        // 如果API不可用，保存到LocalStorage作为后备方案
        localStorage.setItem('account_data', JSON.stringify(accounts));
    }
}

// 从API加载配置
async function loadConfig() {
    console.log('开始加载配置...');
    try {
        const response = await fetch(`${API_BASE_URL}/config`);
        const result = await response.json();
        console.log('配置API响应:', result);
        if (result.success) {
            const config = result.data || {};
            marketers = config.marketers || ["请选择营销人"];
            products = config.products || ["请选择产品名称"];
            console.log('成功加载配置:', { marketers: marketers.length, products: products.length });
        } else {
            console.error('加载配置失败:', result.error);
            // 使用默认配置
            marketers = ["请选择营销人", "张三", "李四", "王五", "赵六"];
            products = ["请选择产品名称", "产品A", "产品B", "产品C", "产品D"];
            saveConfig(); // 保存默认配置
        }
    } catch (e) {
        console.error('加载配置失败:', e);
        // 如果API不可用，尝试从LocalStorage加载
        const config = localStorage.getItem('config');
        if (config) {
            try {
                const parsed = JSON.parse(config);
                marketers = parsed.marketers || ["请选择营销人"];
                products = parsed.products || ["请选择产品名称"];
                console.log('从LocalStorage加载配置:', { marketers: marketers.length, products: products.length });
            } catch (e) {
                console.error('加载本地配置失败:', e);
                marketers = ["请选择营销人"];
                products = ["请选择产品名称"];
            }
        } else {
            // 默认配置
            marketers = ["请选择营销人", "张三", "李四", "王五", "赵六"];
            products = ["请选择产品名称", "产品A", "产品B", "产品C", "产品D"];
            saveConfig(); // 保存默认配置
        }
    }
    
    // 更新下拉框
    updateComboboxes();
}

// 保存配置到API
async function saveConfig() {
    try {
        const config = {
            marketers: marketers,
            products: products
        };
        const response = await fetch(`${API_BASE_URL}/config`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ data: config }),
        });
        const result = await response.json();
        if (result.success) {
            console.log('配置保存成功');
        } else {
            console.error('配置保存失败:', result.error);
            // 如果API保存失败，尝试保存到LocalStorage作为后备方案
            localStorage.setItem('config', JSON.stringify(config));
        }
    } catch (e) {
        console.error('保存配置失败:', e);
        // 如果API不可用，保存到LocalStorage作为后备方案
        const config = {
            marketers: marketers,
            products: products
        };
        localStorage.setItem('config', JSON.stringify(config));
    }
}

// 更新下拉框选项
function updateComboboxes() {
    const marketerSelects = document.querySelectorAll('#marketer, #batchMarketer');
    const productSelects = document.querySelectorAll('#product, .product-select');
    
    // 更新营销人下拉框
    marketerSelects.forEach(select => {
        const currentValue = select.value;
        select.innerHTML = '';
        
        marketers.forEach(marketer => {
            const option = document.createElement('option');
            option.value = marketer;
            option.textContent = marketer;
            select.appendChild(option);
        });
        
        // 尝试恢复之前选中的值
        if (marketers.includes(currentValue)) {
            select.value = currentValue;
        } else {
            select.value = marketers[0];
        }
    });
    
    // 更新产品下拉框
    productSelects.forEach(select => {
        const currentValue = select.value;
        select.innerHTML = '';
        
        products.forEach(product => {
            const option = document.createElement('option');
            option.value = product;
            option.textContent = product;
            select.appendChild(option);
        });
        
        // 尝试恢复之前选中的值
        if (products.includes(currentValue)) {
            select.value = currentValue;
        } else {
            select.value = products[0];
        }
    });
}

// 添加台账记录
function addAccount() {
    const marketer = document.getElementById('marketer').value;
    const product = document.getElementById('product').value;
    const amount = document.getElementById('amount').value;
    const date = document.getElementById('date').value;
    const notes = document.getElementById('notes').value;
    
    // 验证必填项
    if (marketer === "请选择营销人" || !marketer) {
        alert('请选择有效的营销人');
        return;
    }
    
    if (product === "请选择产品名称" || !product) {
        alert('请选择有效的产品名称');
        return;
    }
    
    if (!amount || parseFloat(amount) <= 0) {
        alert('请输入有效的数量（必须大于0）');
        return;
    }
    
    // 计算新ID
    const maxId = accounts.length > 0 ? Math.max(...accounts.map(a => a.id)) : 0;
    const newId = maxId + 1;
    
    // 创建新记录
    const newRecord = {
        id: newId,
        marketer: marketer,
        product: product,
        amount: parseFloat(amount),
        date: date,
        notes: notes
    };
    
    // 添加到数组
    accounts.push(newRecord);
    
    // 保存数据
    saveData();
    
    // 更新显示
    updateAccountList();
    
    // 清空表单
    document.getElementById('accountForm').reset();
    document.getElementById('date').value = new Date().toISOString().split('T')[0];
    
    // 显示成功消息
    alert(`添加成功！编号：${newId}`);
}

// 更新台账列表显示
function updateAccountList() {
    const tbody = document.getElementById('accountsTableBody');
    const recordCount = document.getElementById('recordCount');
    
    // 清空现有内容
    tbody.innerHTML = '';
    
    // 排序数据
    const sortedAccounts = [...accounts].sort((a, b) => {
        let aVal, bVal;
        
        switch (sortConfig.column) {
            case 'id':
            case 'amount':
                aVal = a[sortConfig.column];
                bVal = b[sortConfig.column];
                break;
            default:
                aVal = a[sortConfig.column] || '';
                bVal = b[sortConfig.column] || '';
        }
        
        if (sortConfig.column === 'id' || sortConfig.column === 'amount') {
            // 数值排序
            if (sortConfig.direction === 'asc') {
                return aVal - bVal;
            } else {
                return bVal - aVal;
            }
        } else {
            // 字符串排序
            if (sortConfig.direction === 'asc') {
                return aVal.localeCompare(bVal);
            } else {
                return bVal.localeCompare(aVal);
            }
        }
    });
    
    // 添加记录到表格
    sortedAccounts.forEach(account => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${account.id}</td>
            <td>${escapeHtml(account.marketer)}</td>
            <td>${escapeHtml(account.product)}</td>
            <td>${account.amount}</td>
            <td>${account.date}</td>
            <td>${escapeHtml(account.notes)}</td>
            <td>
                <button class="btn btn-primary btn-sm edit-btn" data-id="${account.id}">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-danger btn-sm delete-btn" data-id="${account.id}">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
    
    // 更新记录数量
    recordCount.textContent = `${accounts.length} 条记录`;
}

// 编辑记录
function editAccount(id) {
    // 查找要编辑的记录
    const account = accounts.find(acc => acc.id === id);
    if (!account) {
        alert('未找到该记录');
        return;
    }
    
    // 填充编辑表单
    document.getElementById('editId').value = account.id;
    document.getElementById('editAmount').value = account.amount;
    document.getElementById('editDate').value = account.date;
    document.getElementById('editNotes').value = account.notes;
    
    // 更新下拉框选项并设置选中值
    updateEditComboboxes();
    document.getElementById('editMarketer').value = account.marketer;
    document.getElementById('editProduct').value = account.product;
    
    // 显示编辑模态框
    const editModal = new bootstrap.Modal(document.getElementById('editModal'));
    editModal.show();
}

// 更新编辑模态框中的下拉框选项
function updateEditComboboxes() {
    // 更新营销人下拉框
    const marketerSelect = document.getElementById('editMarketer');
    const currentMarketer = marketerSelect.value;
    marketerSelect.innerHTML = '';
    
    marketers.forEach(marketer => {
        const option = document.createElement('option');
        option.value = marketer;
        option.textContent = marketer;
        marketerSelect.appendChild(option);
    });
    
    // 尝试恢复之前选中的值
    if (marketers.includes(currentMarketer)) {
        marketerSelect.value = currentMarketer;
    }
    
    // 更新产品下拉框
    const productSelect = document.getElementById('editProduct');
    const currentProduct = productSelect.value;
    productSelect.innerHTML = '';
    
    products.forEach(product => {
        const option = document.createElement('option');
        option.value = product;
        option.textContent = product;
        productSelect.appendChild(option);
    });
    
    // 尝试恢复之前选中的值
    if (products.includes(currentProduct)) {
        productSelect.value = currentProduct;
    }
}

// 保存编辑后的记录
function saveEditedAccount() {
    // 获取表单数据
    const id = parseInt(document.getElementById('editId').value);
    const marketer = document.getElementById('editMarketer').value;
    const product = document.getElementById('editProduct').value;
    const amount = document.getElementById('editAmount').value;
    const date = document.getElementById('editDate').value;
    const notes = document.getElementById('editNotes').value;
    
    // 验证必填字段
    if (!marketer || !product || !amount || !date) {
        alert('请填写所有必填字段');
        return;
    }
    
    // 查找并更新记录
    const index = accounts.findIndex(acc => acc.id === id);
    if (index !== -1) {
        accounts[index] = {
            id: id,
            marketer: marketer,
            product: product,
            amount: parseFloat(amount),
            date: date,
            notes: notes
        };
        
        // 保存数据
        saveData();
        
        // 更新显示
        updateAccountList();
        
        // 隐藏模态框
        const editModal = bootstrap.Modal.getInstance(document.getElementById('editModal'));
        editModal.hide();
        
        // 显示成功消息
        alert('记录更新成功！');
    } else {
        alert('未找到该记录');
    }
}

// 删除记录
function deleteAccount(id) {
    if (!confirm(`确定要删除编号为 ${id} 的记录吗？`)) {
        return;
    }
    
    // 过滤掉要删除的记录
    accounts = accounts.filter(account => account.id !== id);
    
    // 保存数据
    saveData();
    
    // 更新显示
    updateAccountList();
}

// 排序功能
function sortBy(column) {
    if (sortConfig.column === column) {
        // 切换排序方向
        sortConfig.direction = sortConfig.direction === 'asc' ? 'desc' : 'asc';
    } else {
        // 新的排序列，默认升序
        sortConfig.column = column;
        sortConfig.direction = 'asc';
    }
    
    // 更新显示
    updateAccountList();
    
    // 更新排序图标
    updateSortIcons();
}

// 更新排序图标
function updateSortIcons() {
    // 清除所有排序图标
    document.querySelectorAll('#accountsTable th[data-sort] i').forEach(icon => {
        icon.className = 'bi bi-arrow-down-up';
    });
    
    // 设置当前排序列的图标
    const currentTh = document.querySelector(`#accountsTable th[data-sort="${sortConfig.column}"]`);
    if (currentTh) {
        const icon = currentTh.querySelector('i');
        if (sortConfig.direction === 'asc') {
            icon.className = 'bi bi-arrow-up';
        } else {
            icon.className = 'bi bi-arrow-down';
        }
    }
}

// 导出数据为CSV
function exportData() {
    if (accounts.length === 0) {
        alert('没有数据可以导出');
        return;
    }
    
    // 定义CSV列名
    const headers = ['id', 'marketer', 'product', 'amount', 'date', 'notes'];
    const headerNames = ['ID', '营销人', '产品名称', '数量', '日期', '备注'];
    
    // 创建CSV内容
    let csvContent = '\uFEFF' + headerNames.join(',') + '\n'; // 添加BOM以支持中文
    
    accounts.forEach(account => {
        const row = headers.map(header => {
            const value = account[header];
            // 转义包含逗号或引号的值
            return typeof value === 'string' && (value.includes(',') || value.includes('"')) 
                ? `"${value.replace(/"/g, '""')}"` 
                : value;
        }).join(',');
        csvContent += row + '\n';
    });
    
    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    const dateStr = new Date().toISOString().split('T')[0].replace(/-/g, '');
    link.setAttribute('href', url);
    link.setAttribute('download', `台账导出${dateStr}.csv`);
    link.style.visibility = 'hidden';
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 打开管理窗口
function openManageWindow() {
    console.log('打开管理窗口');
    // 显示模态框
    const manageModal = new bootstrap.Modal(document.getElementById('manageModal'));
    manageModal.show();
    
    // 绑定管理事件
    bindManageEvents();
    
    // 更新列表显示
    updateManageLists();
}

// 检查模态框中的关键元素是否存在
function checkModalElements() {
    const elementsToCheck = [
        'manageModal',
        'manageModalLabel',
        'manageTabs',
        'manageTabsContent',
        'marketer-tab-pane',
        'product-tab-pane',
        'marketer-tab',
        'product-tab',
        'newMarketer',
        'newProduct',
        'addMarketerBtn',
        'addProductBtn',
        'marketerList',
        'productList'
    ];
    
    elementsToCheck.forEach(elementId => {
        const element = document.getElementById(elementId);
        console.log(`${elementId}: ${element ? '找到' : '未找到'}`);
    });
}

// 自定义模态框显示方法
function showCustomModal(modalElement) {
    console.log('使用自定义方式显示模态框');
    try {
        modalElement.style.display = 'block';
        modalElement.classList.add('show');
        document.body.classList.add('modal-open');
        
        // 添加关闭事件
        const closeButtons = modalElement.querySelectorAll('[data-bs-dismiss="modal"]');
        closeButtons.forEach(button => {
            button.addEventListener('click', function() {
                modalElement.style.display = 'none';
                modalElement.classList.remove('show');
                document.body.classList.remove('modal-open');
            });
        });
        
        // 点击模态框背景关闭
        modalElement.addEventListener('click', function(e) {
            if (e.target === modalElement) {
                modalElement.style.display = 'none';
                modalElement.classList.remove('show');
                document.body.classList.remove('modal-open');
            }
        });
        
        console.log('自定义模态框显示成功');
    } catch (e) {
        console.error('自定义模态框显示失败:', e);
        alert('无法打开管理窗口，请检查页面结构');
    }
}

// 更新管理列表
function updateManageLists() {
    // 更新营销人列表
    const marketerList = document.getElementById('marketerList');
    if (marketerList) {
        marketerList.innerHTML = '';
        
        // 不再使用slice(1)，显示所有营销人（除了第一个"请选择"选项）
        for (let i = 1; i < marketers.length; i++) {
            const marketer = marketers[i];
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${i}</td>
                <td>${escapeHtml(marketer)}</td>
                <td>
                    <button class="btn btn-danger btn-sm remove-marketer" data-name="${escapeHtml(marketer)}">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;
            marketerList.appendChild(row);
        }
    }
    
    // 更新产品列表
    const productList = document.getElementById('productList');
    if (productList) {
        productList.innerHTML = '';
        
        // 不再使用slice(1)，显示所有产品（除了第一个"请选择"选项）
        for (let i = 1; i < products.length; i++) {
            const product = products[i];
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${i}</td>
                <td>${escapeHtml(product)}</td>
                <td>
                    <button class="btn btn-danger btn-sm remove-product" data-name="${escapeHtml(product)}">
                        <i class="bi bi-trash"></i>
                    </button>
                </td>
            `;
            productList.appendChild(row);
        }
    }
}

// 添加营销人
function addMarketer() {
    const newMarketerInput = document.getElementById('newMarketer');
    if (!newMarketerInput) {
        console.error('未找到营销人输入框 #newMarketer');
        alert('页面元素缺失，请刷新页面后重试');
        return;
    }
    
    const newMarketer = newMarketerInput.value.trim();
    
    if (!newMarketer) {
        alert('请输入营销人名称');
        newMarketerInput.focus();
        return;
    }
    
    if (marketers.includes(newMarketer)) {
        alert('该营销人已存在');
        return;
    }
    
    marketers.push(newMarketer);
    saveConfig();
    updateManageLists();
    updateComboboxes();
    
    // 清空输入框
    newMarketerInput.value = '';
    newMarketerInput.focus();
    
    // 显示成功消息
    alert('营销人添加成功');
}

// 删除营销人
function removeMarketer(name) {
    if (!confirm(`确定要删除营销人 "${name}" 吗？`)) {
        return;
    }
    
    marketers = marketers.filter(m => m !== name);
    saveConfig();
    updateManageLists();
    updateComboboxes();
    
    // 显示成功消息
    alert('营销人删除成功');
}

// 添加产品
function addProduct() {
    const newProductInput = document.getElementById('newProduct');
    if (!newProductInput) {
        console.error('未找到产品输入框 #newProduct');
        alert('页面元素缺失，请刷新页面后重试');
        return;
    }
    
    const newProduct = newProductInput.value.trim();
    
    if (!newProduct) {
        alert('请输入产品名称');
        newProductInput.focus();
        return;
    }
    
    if (products.includes(newProduct)) {
        alert('该产品已存在');
        return;
    }
    
    products.push(newProduct);
    saveConfig();
    updateManageLists();
    updateComboboxes();
    
    // 清空输入框
    newProductInput.value = '';
    newProductInput.focus();
    
    // 显示成功消息
    alert('产品添加成功');
}

// 删除产品
function removeProduct(name) {
    if (!confirm(`确定要删除产品 "${name}" 吗？`)) {
        return;
    }
    
    products = products.filter(p => p !== name);
    saveConfig();
    updateManageLists();
    updateComboboxes();
    
    // 显示成功消息
    alert('产品删除成功');
}

// 打开批量录入窗口
function openBatchEntry() {
    // 清空产品行
    document.getElementById('batchProductsTable').innerHTML = '';
    
    // 添加一个默认产品行
    addProductRow();
    
    // 显示模态框
    const batchModal = new bootstrap.Modal(document.getElementById('batchModal'));
    batchModal.show();
}

// 添加产品行
function addProductRow() {
    const productRows = document.getElementById('batchProductsTable');
    const row = document.createElement('tr');
    row.className = 'product-row';
    row.innerHTML = `
        <td>
            <select class="form-select product-select" required>
                <option value="">请选择产品名称</option>
            </select>
        </td>
        <td>
            <input type="number" class="form-control amount-input" placeholder="数量" step="0.01" min="0" required>
        </td>
        <td>
            <input type="text" class="form-control notes-input" placeholder="备注">
        </td>
        <td>
            <button type="button" class="btn btn-danger btn-sm remove-product-row">
                <i class="bi bi-trash"></i>
            </button>
        </td>
    `;
    productRows.appendChild(row);
    
    // 更新新添加的下拉框
    const newSelect = row.querySelector('.product-select');
    products.forEach(product => {
        const option = document.createElement('option');
        option.value = product;
        option.textContent = product;
        newSelect.appendChild(option);
    });
    
    // 绑定删除行事件
    row.querySelector('.remove-product-row').addEventListener('click', function() {
        if (document.querySelectorAll('.product-row').length > 1) {
            row.remove();
        } else {
            alert('至少需要保留一个产品行');
        }
    });
}

// 保存批量记录
function saveBatchRecords() {
    const marketer = document.getElementById('batchMarketer').value;
    const date = document.getElementById('batchDate').value;
    
    // 验证营销人
    if (marketer === "请选择营销人" || !marketer) {
        alert('请选择营销人');
        return;
    }
    
    // 收集产品记录
    const productRows = document.querySelectorAll('.product-row');
    const records = [];
    
    for (const row of productRows) {
        const product = row.querySelector('.product-select').value;
        const amount = row.querySelector('.amount-input').value;
        
        // 验证产品
        if (product === "请选择产品名称" || !product) {
            alert('请选择所有产品名称');
            return;
        }
        
        // 验证数量
        if (!amount || parseFloat(amount) <= 0) {
            alert(`产品 "${product}" 的数量输入无效`);
            return;
        }
        
        records.push({
            product: product,
            amount: parseFloat(amount)
        });
    }
    
    // 验证至少有一个产品
    if (records.length === 0) {
        alert('请添加至少一个产品');
        return;
    }
    
    // 计算起始ID
    const maxId = accounts.length > 0 ? Math.max(...accounts.map(a => a.id)) : 0;
    let currentId = maxId;
    
    // 添加所有记录
    records.forEach(record => {
        currentId++;
        const newRecord = {
            id: currentId,
            marketer: marketer,
            product: record.product,
            amount: record.amount,
            date: date,
            notes: ""
        };
        accounts.push(newRecord);
    });
    
    // 保存数据
    saveData();
    
    // 更新显示
    updateAccountList();
    
    // 关闭模态框
    const batchModal = bootstrap.Modal.getInstance(document.getElementById('batchModal'));
    batchModal.hide();
    
    // 显示成功消息
    alert(`批量录入成功，共添加 ${records.length} 条记录`);
}

// 工具函数：转义HTML特殊字符
function escapeHtml(text) {
    if (typeof text !== 'string') return text;
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}